01. Intro to Preferences

Intro to Preferences

In this mini-lesson, we'll learn how to customize the list of earthquakes that are shown in the app by adding a settings screen to the app. The user will be able to select a minimum magnitude size for earthquakes that should be displayed , and to change whether they'd like to see earthquakes ordered by magnitude or time. To add this functionality to the app, we'll add a new settings activity and use the user's preferences to change the URL used to query for earthquakes.

One of the foundations of Android is that it should "Make me amazing". That often means that each user needs a slightly different experience, tailored to them and their particular preferences. Hence, we need a way for the user to adjust preferences in our app, and remember which preferences they've chosen. Say, for instance, you ask the user for the minimum magnitude of earthquake they're interested in, and they say "5". Well now every time you go to get earthquakes for the user, you need to get them only earthquakes with a magnitude greater than 5, even after they've closed and reopened your app. Even after they're turned off their phone, and turned it back on again!

Storing data on a user's device (which is referred to more generally as data persistence), is a huge topic that will be the topic of the entire next course.

For now though, the designers of Android anticipated the need to store small amounts of data to keep track of user preferences, so there's an Android component to handle this for us.

SharedPreferences

A preference is really just a string key associated with a primitive type, String, or set of Strings. Android will hold onto that data for you even when the app is closed, and even if the phone is turned off. Android provides a SharedPreferences class to make getting and setting preferences straight-forward. SharedPreferences handles all the details of reading and writing preference data to the persistent storage (which is a file) on the device.

In addition to storing the preference, we need to provide a way for the user to edit the preferences in your app via the user interface. For a preference that's a number, we need to let the user type in a number. For a preference that should be selected from a list, we need to present a list of options, and let the user pick one, and so on.

We could make such an Activity ourselves, but Android provides a class called PreferenceFragment that shows a list of UI widgets (Preference objects) for easily editing all sort of preferences.

In case it snuck past you, that term Fragment is new. Let's talk about what that means.